"use client";

import { useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { ThumbsUp, MessageSquare, MoreHorizontal } from "lucide-react";

interface Comment {
  id: string;
  content: string;
  user: {
    name: string;
    avatar: string;
  };
  likeCount: string;
  replyCount?: string;
  timestamp: string;
  replies?: Comment[];
}

interface CommentsProps {
  comments: Comment[];
  totalCount: string;
}

export default function Comments({ comments, totalCount }: CommentsProps) {
  const [commentText, setCommentText] = useState("");
  const [expandedComments, setExpandedComments] = useState<Record<string, boolean>>({});
  const [likedComments, setLikedComments] = useState<Record<string, boolean>>({});

  const handleCommentSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // Here you would normally send the comment to your backend
    alert(`评论已提交: ${commentText}`);
    setCommentText("");
  };

  const toggleReplies = (commentId: string) => {
    setExpandedComments((prev) => ({
      ...prev,
      [commentId]: !prev[commentId],
    }));
  };

  const toggleLike = (commentId: string) => {
    setLikedComments((prev) => ({
      ...prev,
      [commentId]: !prev[commentId],
    }));
  };

  const sortOptions = ["最热", "最新", "UP主关注"];

  return (
    <div className="bg-white rounded-lg shadow-sm p-4 mt-6">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-lg font-bold">评论 ({totalCount})</h2>
        <div className="flex space-x-4">
          {sortOptions.map((option, index) => (
            <button
              key={index}
              className={`text-sm ${index === 0 ? "text-primary font-medium" : "text-gray-500"}`}
            >
              {option}
            </button>
          ))}
        </div>
      </div>

      {/* Comment form */}
      <div className="flex mb-6">
        <Avatar className="h-8 w-8 mr-3 flex-shrink-0">
          <AvatarImage src="https://ext.same-assets.com/565216724/2967821683.avif" alt="Your profile" />
          <AvatarFallback>YO</AvatarFallback>
        </Avatar>
        <form onSubmit={handleCommentSubmit} className="flex-1 flex gap-2">
          <Input
            value={commentText}
            onChange={(e) => setCommentText(e.target.value)}
            placeholder="发一条友善的评论"
            className="flex-1"
          />
          <Button
            type="submit"
            disabled={!commentText.trim()}
            className="bg-secondary hover:bg-secondary/90 text-white"
          >
            发布
          </Button>
        </form>
      </div>

      {/* Comments list */}
      {comments.length > 0 ? (
        <div className="space-y-6">
          {comments.map((comment) => (
            <div key={comment.id} className="border-b pb-4 last:border-b-0 last:pb-0">
              <div className="flex">
                <Avatar className="h-8 w-8 mr-3 flex-shrink-0">
                  <AvatarImage src={comment.user.avatar} alt={comment.user.name} />
                  <AvatarFallback>{comment.user.name.slice(0, 2)}</AvatarFallback>
                </Avatar>
                <div className="flex-1">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-gray-900">{comment.user.name}</span>
                    <span className="text-xs text-gray-500">{comment.timestamp}</span>
                  </div>
                  <p className="mt-1 text-sm text-gray-700">{comment.content}</p>

                  <div className="flex items-center mt-2 text-gray-500 text-xs">
                    <button
                      onClick={() => toggleLike(comment.id)}
                      className={`flex items-center ${likedComments[comment.id] ? 'text-primary' : ''}`}
                    >
                      <ThumbsUp className="w-3.5 h-3.5 mr-1" />
                      <span>
                        {likedComments[comment.id]
                          ? (parseInt(comment.likeCount.replace("k", "000")) + 1).toString()
                          : comment.likeCount}
                      </span>
                    </button>

                    {comment.replyCount && (
                      <button
                        onClick={() => toggleReplies(comment.id)}
                        className="flex items-center ml-4"
                      >
                        <MessageSquare className="w-3.5 h-3.5 mr-1" />
                        <span>{comment.replyCount}</span>
                      </button>
                    )}

                    <button className="ml-4">
                      <MoreHorizontal className="w-3.5 h-3.5" />
                    </button>
                  </div>

                  {/* Comment replies */}
                  {expandedComments[comment.id] && comment.replies && comment.replies.length > 0 && (
                    <div className="mt-3 pl-4 space-y-3 border-l-2 border-gray-100">
                      {comment.replies.map((reply) => (
                        <div key={reply.id} className="flex">
                          <Avatar className="h-6 w-6 mr-2 flex-shrink-0">
                            <AvatarImage src={reply.user.avatar} alt={reply.user.name} />
                            <AvatarFallback>{reply.user.name.slice(0, 2)}</AvatarFallback>
                          </Avatar>
                          <div>
                            <div className="flex items-center">
                              <span className="text-xs font-medium text-gray-900">{reply.user.name}</span>
                              <span className="text-xs text-gray-500 ml-2">{reply.timestamp}</span>
                            </div>
                            <p className="mt-1 text-xs text-gray-700">{reply.content}</p>

                            <div className="flex items-center mt-1 text-gray-500 text-xs">
                              <button
                                onClick={() => toggleLike(reply.id)}
                                className={`flex items-center ${likedComments[reply.id] ? 'text-primary' : ''}`}
                              >
                                <ThumbsUp className="w-3 h-3 mr-1" />
                                <span>
                                  {likedComments[reply.id]
                                    ? (parseInt(reply.likeCount.replace("k", "000")) + 1).toString()
                                    : reply.likeCount}
                                </span>
                              </button>
                              <button className="ml-3">
                                <MoreHorizontal className="w-3 h-3" />
                              </button>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-center py-8 text-gray-500">
          <p>暂无评论，快来抢沙发吧！</p>
        </div>
      )}

      {comments.length > 0 && (
        <div className="mt-4 text-center">
          <button className="text-sm text-primary hover:underline">
            查看更多评论
          </button>
        </div>
      )}
    </div>
  );
}
